package com.example.scanner.zxing.qrcode;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zwg
 * @date 2025/10/13 17:09
 */
public class QRCodeGenerator {

    // 二维码颜色
    private static final int QR_COLOR = 0xFF000000; // 默认黑色
    // 二维码背景色
    private static final int BG_WHITE = 0xFFFFFFFF; // 白色

    /**
     * 生成带Logo的二维码图片
     *
     * @param content 二维码内容
     * @param width 二维码宽度
     * @param height 二维码高度
     * @param logoPath Logo图片路径
     * @param outputPath 生成的二维码保存路径
     * @throws Exception 可能抛出的异常
     */
    public static void generateQRCodeWithLogo(String content, int width, int height,
                                              String logoPath, String outputPath) throws Exception {
        // 设置二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 高容错级别，便于添加Logo
        hints.put(EncodeHintType.MARGIN, 1);

        // 生成二维码矩阵
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.QR_CODE, width, height, hints);

        // 生成二维码图片
        BufferedImage qrImage = toBufferedImage(bitMatrix);

        // 添加Logo
        if (logoPath != null && !logoPath.isEmpty()) {
            qrImage = addLogo(qrImage, logoPath);
        }

        // 保存二维码图片
        File outputFile = new File(outputPath);
        ImageIO.write(qrImage, "png", outputFile);
    }

    /**
     * 将BitMatrix转换为BufferedImage
     */
    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? QR_COLOR : BG_WHITE);
            }
        }

        return image;
    }

    /**
     * 给二维码添加Logo
     */
    private static BufferedImage addLogo(BufferedImage qrImage, String logoPath) throws IOException {
        // 读取Logo图片
        File logoFile = new File(logoPath);
        if (!logoFile.exists()) {
            throw new IOException("Logo文件不存在: " + logoPath);
        }

        BufferedImage logoImage = ImageIO.read(logoFile);

        // 获取二维码和Logo的宽度和高度
        int qrWidth = qrImage.getWidth();
        int qrHeight = qrImage.getHeight();
        int logoWidth = logoImage.getWidth();
        int logoHeight = logoImage.getHeight();

        // 设置Logo大小为二维码的1/5
        if (logoWidth > qrWidth / 5 || logoHeight > qrHeight / 5) {
            logoWidth = qrWidth / 5;
            logoHeight = qrHeight / 5;

            // 调整Logo大小
            Image tempImage = logoImage.getScaledInstance(logoWidth, logoHeight, Image.SCALE_SMOOTH);
            BufferedImage resizedLogo = new BufferedImage(logoWidth, logoHeight, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g = resizedLogo.createGraphics();
            g.drawImage(tempImage, 0, 0, null);
            g.dispose();
            logoImage = resizedLogo;
        }

        // 计算Logo放置的位置（居中）
        int x = (qrWidth - logoWidth) / 2;
        int y = (qrHeight - logoHeight) / 2;

        // 在二维码上绘制Logo，保持原有颜色
        Graphics2D g = qrImage.createGraphics();
        // 如果Logo有透明背景，这里的绘制方式会保留透明度
        g.drawImage(logoImage, x, y, logoWidth, logoHeight, null);

        // 可选：给Logo添加边框
        // g.setStroke(new BasicStroke(2));
        // g.setColor(Color.WHITE);
        // g.drawRect(x, y, logoWidth, logoHeight);

        g.dispose();

        return qrImage;
    }

    public static void main(String[] args) {
        try {
            /*// 示例：生成带Logo的二维码
            String content = "https://www.example.com"; // 二维码内容
            int width = 300; // 二维码宽度
            int height = 300; // 二维码高度
            String logoPath = "/Users/mac/temp/hui_logo.png"; // Logo图片路径
            String outputPath = "/Users/mac/temp/qrcode_005.png"; // 生成的二维码保存路径


            generateQRCodeWithLogo(content, width, height, logoPath, outputPath);
            System.out.println("二维码生成成功，保存路径：" + outputPath);*/

            String imgPath = "/Users/mac/temp/qrcode_007.png";
            String logoPath = "/Users/mac/temp/hui_logo.png";
            String content = "https://www.example.com";
            try {
                QRCodeUtil.generateQRCodeWithColorLogo(content,300,300,logoPath, imgPath);
                System.out.println("二维码生成成功:"+imgPath);
            }catch (Exception e){
                e.printStackTrace();
            }
        } catch (Exception e) {
            System.err.println("生成二维码失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
}
